/*
 * @Author: Penk
 * @LastEditors: Penk
 * @LastEditTime: 2022-07-14 11:28:58
 * @FilePath: \puppeteer-demo\scripts\main.js
 */

import $root from './script.js';
import chalk from 'chalk';

async function autoTi(puppeteerObj) {
  // 初始化
  await $root.init(puppeteerObj.page, puppeteerObj.browser);
  var page = puppeteerObj.page;

  // 监听请求
  function logRequest(interceptedRequest) {
    // if (interceptedRequest.url().includes('https://www.ti.com.cn/store/ti/zh/tinotify/notifyEmail')) {
    //   console.log('A request was made:', interceptedRequest.url());
    // }
  }
  page.on('request', logRequest);

  // 监听响应
  function logResponse(response) {
    // if (response.url().includes('https://www.ti.com.cn/store/ti/zh/tinotify/notifyEmail')) {
    //   console.table([{
    //     name: 'status',
    //     value: response.status()
    //   }]);
    // }
  }
  page.on('response', logResponse);

  page.on('load', async () => {
    var href = await $root.getUrl();
    var pageName = '';
    var rand = Math.floor(Math.random() * 10000);

    // 转成 .cn 域名
    // if (href.indexOf("https://www.ti.com.cn/") === -1 && href.indexOf("https://www.ti.com/" !== -1)) {
    //   page.eval
    //   return;
    // }

    if (href == "https://www.ti.com.cn/") {
      pageName = '首页';
    } else if (
      href.indexOf("https://www.ti.com.cn/sitesearch") !== -1) {
      pageName = '搜索结果页';
    } else if (
      href.indexOf("https://www.ti.com.cn/store/ti/zh/p/product") !== -1) {
      pageName = '商品详情页';
    }
    console.time("=========" + pageName + rand)

    switch (pageName) {
      case '首页': {
        await $root.distributionArea();

        // 首页
        await $root.homePage();
        // var target = 'https://www.ti.com.cn/store/ti/zh/p/product/?p=DRV8434PWPR&_ticdt=MTY0OTgzNTM5OXwwMTgwMjFkOWIzMDUwMDAyZDRjZTE4MDE1YTFkMDUwMGUwMDE2MDBlMDBiZDB8R0ExLjMuNjkxMTU5MDg3LjE2NDk4MzUzNTg&keyMatch=DRV8434PWPR&tisearch=search-everything&usecase=OPN';
        // page.goto(target);
        break;
      }
      case '搜索结果页': {
        await $root.searchPage();
        break;
      }
      case '商品详情页': {
        await $root.productDetail();
        break;
      }
      default:
        break;
    }

    console.timeEnd("=========" + pageName + rand)
  });

  // 初始化页面
  page.goto('https://www.ti.com.cn/', {
    waitUntil: 'domcontentloaded'
  });
}

async function taobaoAutoLogin(puppeteerObj) {
  var {
    browser,
    page
  } = puppeteerObj;

  // 初始化页面
  page.goto('https://login.taobao.com/member/login.jhtml?style=mini&newMini2=true&from=alimama', {
    waitUntil: 'domcontentloaded'
  });

  const $username = await page.$('#fm-login-id');
  const $password = await page.$('#fm-login-password');
  const $btn = await page.$('.password-login');

  // 输入账号
  await $username.type(username);
  await page.click('body');

  page.waitForResponse(response => {
    return response.url().includes('newlogin/account/check.do');
  }).then(async response => {});

  // 输入密码
  await $password.type(password);

  response.json().then(async res => {
    // 有验证码显示模拟输入验证码
    if (res.content.data.isCheckCodeShowed) {
      const $code = await page.$('#nocaptcha-password');
      const size = await $code.boundingBox();
      await page.mouse.move(size.x, size.y);
      await page.mouse.down();
      await page.mouse.move(size.x + 208, size.y, {
        steps: 4
      });
      await page.waitFor(333);
    }
    await $btn.click();
    await page.waitForNavigation();

    console.log('login successful!');
  })
}

export default {
  autoTi,
  taobaoAutoLogin
}